import { ICalculator, ICalculatorParams } from '../types';
import { calculateMonthlyInterestRate, calculateNumToStr, calculateWalkMonthly } from '../util';

const reducingBalanceCalculator: ICalculator = (params: ICalculatorParams) => {
  const { principal, interestRate, loanTerm } = params;

  const monthlyInterestRate = calculateMonthlyInterestRate(interestRate);
  const monthlyPrincipal = principal / loanTerm;

  const calculateMonthly = (month: number) => {
    const remainingPrincipal = principal - ((month + 1) * monthlyPrincipal); // prettier-ignore
    const interestPrincipal = principal - (month * monthlyPrincipal); // prettier-ignore
    const interestPayment = interestPrincipal * monthlyInterestRate;
    const monthlyPayment = monthlyPrincipal + (monthlyInterestRate * interestPrincipal); // prettier-ignore

    return {
      monthlyPayment: calculateNumToStr(monthlyPayment),
      interestPayment: calculateNumToStr(interestPayment),
      monthlyPrincipal: calculateNumToStr(monthlyPrincipal),
      remainingPrincipal: calculateNumToStr(remainingPrincipal),
    };
  };

  return calculateWalkMonthly(params, calculateMonthly);
};

export default reducingBalanceCalculator;
